package stock;

import java.util.ArrayList;
import java.util.Arrays;

public class Solution3 {

    public static void main(String[] args) {
        Solution3 solution3 = new Solution3();
        int[] prices = {3,3,5,0,0,3,1,4};
        int res =solution3.maxProfit(prices);
        System.out.println(res);
    }

    //最低点前有一次最大获利，最低点后有一次最大获利
    //两次获利相加 就是结果
    //1找到最低点
    //2最低点前的最大获利
    //3最低点后的最大获利
    public int maxProfit(int[] prices){
        int profit = 0;
        int min =0;
        int minIndex =0;
        for (int i = 0; i < prices.length; i++) {
            if(i==0){
                min =  prices[i];
                minIndex = i;
            }else{
               if(prices[i]<min){
                   min = prices[i];
                   minIndex = i;
               }
            }
        }
        //最低点前的最大利润
        int[] prices1 = Arrays.copyOf(prices,minIndex+1);
        int profit1 = maxProfit2(prices1);

        //最低点后的最大利润
        int[] prices2 =Arrays.copyOfRange(prices,minIndex+1,prices.length);
        int profit2 = maxProfit2(prices2);

        profit = profit1+profit2;
        return profit;
    }

    //如果后一条数据大于前一条数据，就计算其差，所有差的累计就是结果
    public int maxProfit2(int[] prices){
        int result = 0;
        for (int i = 0; i < prices.length; i++) {
            if(i<prices.length-1){
                if(prices[i+1]>prices[i]){
                    result = result+ (prices[i+1]-prices[i]);
                }
            }
        }
        return result;
    }


}
